package com.haidechizi.fastadmin.modules.oss.servlet;

import com.haidechizi.fastadmin.common.utils.GlobalUtils;
import com.haidechizi.fastadmin.modules.oss.utils.OssUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.util.UriUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * @author wangdejun
 */
@Slf4j
@WebServlet(name = "UserFileServlet", urlPatterns = "/" + OssUtils.userFile +"/*")
public class UserFileServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    public void fileOutputStream(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        String filepath = request.getRequestURI();
        int index = filepath.indexOf(OssUtils.userFile);
        if (index >= 0) {
            filepath = filepath.substring(index + OssUtils.userFile.length());
        }
        filepath = UriUtils.decode(filepath, "UTF-8");
        File file = new File(GlobalUtils.getFilePath() + OssUtils.userFile + filepath);
        try {
            FileCopyUtils.copy(new FileInputStream(file), response.getOutputStream());
            response.setHeader("Content-Type", "application/octet-stream");
            return;
        } catch (FileNotFoundException e) {
            log.error("文件不存在", e);
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        fileOutputStream(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        fileOutputStream(request, response);
    }
}
